<?php

namespace app\api\logic;

use think\facade\Db;
use app\data\util\HttpUtil;
use think\exception\ValidateException;
use think\facade\Cache;
use app\api\logic\ApiOrderLogic;

use app\order\logic\OrderSourceLogic;

class ApiOrderDisputeLogic extends BasicLogic
{
    public function __construct()
    {

    }

    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc paypal获取list
     * @author zhangheng
     */
    public function dispute_paypal($params = [])
    {
        $dispute_paypal = Config('Logisticskey.dispute_paypal');
        foreach ($dispute_paypal as $k=>$v) {
            $this->dispute_paypal_info($v,$params);
        }
        return json(DefaultResponse(200, true, '操作成功'));
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc paypal获取list
     * @author zhangheng
     */
    public function dispute_paypal_info($config,$params = [])
    {
        //type 1拉取历史 2拉取实时创建 3实时更新
        $type    = $params['type']  ??  1;
        $api_type    = $config['api_type'];
        $url = $config['path']."".$config['disputes'];
        switch ($type) {
            case '1'://拉取历史
                $order_dispute = Db::name('order_dispute_paypal')
                    ->where(['type' => 'paypal'])
                    ->where(['api_type' => $api_type])
                    ->order('update_time asc')
                    ->find();
                if(!empty($order_dispute)){
                    $url = $url . '?update_time_before=' . $order_dispute['update_time'];
                }
                break;
            case '2'://2拉取实时
                $order_dispute = Db::name('order_dispute_paypal')
                    ->where(['type' => 'paypal'])
                    ->where(['api_type' => $api_type])
                    ->order('create_time desc')->find();
                    if(!empty($order_dispute)){
                        $url = $url . '?start_time=' . $order_dispute['create_time'];
                    }
                break;
            case '3'://3实时更新
                $order_dispute = Db::name('order_dispute_paypal')
                    ->where(['type' => 'paypal'])
                    ->where(['api_type' => $api_type])
                    ->order('update_time desc')
                    ->find();
                    if(!empty($order_dispute)){
                        $url = $url . '?update_time_after=' . $order_dispute['update_time'];
                    }
                break;
            default:
        }
        //贝宝争议
        $data = HttpUtil::getUrlPaypal($url,$config);
        if ($data) {
            if (!empty($data['error'])) {
                $arr_error['type'] = 'paypal_error';
                $arr_error['api_type'] = $api_type;
                $arr_error['json'] = json_encode($data, true);
                Db::name('order_dispute_paypal')->insert($arr_error);
                return $data['error_description'];
            }
            if (isset($data['items']) && !empty($data['items']) && is_array($data['items'])) {
                $orders = $data['items'];
                date_default_timezone_set('Asia/Shanghai');
                foreach ($orders as  $order) {
                    $dispute_info = Db::name('order_dispute_paypal')->where('dispute_id',$order['dispute_id'])->find();
                    
                    $arr['type'] = 'paypal';
                    $arr['create_time'] = $order['create_time'];
                    $arr['update_time'] = $order['update_time'];
                    $arr['status'] = $order['status'] ?? "";
                    $arr['amount'] = $order['dispute_amount']['value'] ?? "";
                    $arr['currency'] = $order['dispute_amount']['currency_code'] ?? "";
                    $arr['outcome'] = $order['outcome'] ?? "";
                    $arr['api_type'] = $api_type;
                    $arr['href'] = $order['links'][0]['href'];
                    $arr['json'] = json_encode($order, true);
                    if ($dispute_info) {
                        if(strtotime($dispute_info['update_time']) > strtotime($arr['update_time'])){
                            Db::name('order_dispute_paypal')->where(['dispute_id' => $order['dispute_id']])->update($arr);
                        }
                    } else {
                        $arr['dispute_id'] = $order['dispute_id'];
                        Db::name('order_dispute_paypal')->insert($arr);
                    }
                }
            }
        }
        return true;
    }

    /**
    * @desc    查询订单交易API---详情检查
    * @date    2024/8/23
    * @author  zhangheng
    */
    public function dispute_paypal_inspect()
    {
        $order_dispute_paypal = Db::name('order_dispute_paypal')
            ->where('seller_transaction_id','')
            ->order('href_time asc')
            ->find();
        if(empty($order_dispute_paypal)){
            return json(DefaultResponse(200, true, '完成'));
        }
        //提前更新
        $arr['href_time'] = time();
        Db::name('order_dispute_paypal')->where(['id' => $order_dispute_paypal['id']])->update($arr);  
        //后续api请求超时

        $dispute_paypal = Config('Logisticskey.dispute_paypal');
        foreach ($dispute_paypal as $k=>$v) {
            if($v['api_type'] == $order_dispute_paypal['api_type']){
                $config = $v;
                break;
            }
        }
        if(empty($config)){
            return json(DefaultResponse(200, true, '配置错误'));
        }
        $href = $order_dispute_paypal['href'];
        $data = HttpUtil::getUrlPaypal($href,$config);
        if ($data && empty($data['error']) && isset($data['disputed_transactions'][0])) {
            $disputed_transactions = $data['disputed_transactions'][0];
            $arr['customer_name'] = $disputed_transactions['buyer']['name'] ?? "";
            $arr['seller_transaction_id'] = $disputed_transactions['seller_transaction_id'] ?? "";
            $arr['invoice_number'] = $disputed_transactions['invoice_number'] ?? "";
            if(isset($disputed_transactions['items'][0])){
                $disputed_items = $disputed_transactions['items'][0];
                if(!empty($disputed_items)){
                    if(isset($disputed_items['item_name'])){
                        $arr['item_name'] = $disputed_items['item_name'];
                    }
                    if(isset($disputed_items['item_quantity'])){
                        $arr['item_quantity'] = $disputed_items['item_quantity'];
                    }
                    if(isset($disputed_items['item_description'])){
                        $arr['item_description'] = $disputed_items['item_description'];
                    }
                }
            }
            $arr['reason'] = $data['reason'] ?? "";
            Db::name('order_dispute_paypal')->where(['id' => $order_dispute_paypal['id']])->update($arr);
        }
        return json(DefaultResponse(200, true, '操作成功'));
    }
    


    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc stripe获取list
     * @author zhangheng
     */
    public function dispute_stripe($params = [])
    {
        $dispute_stripe = Config('Logisticskey.dispute_stripe');
        foreach ($dispute_stripe as $k=>$v) {
            $this->dispute_stripe_info($v,$params);
        }
        return json(DefaultResponse(200, true, '操作成功'));
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc stripe获取list
     * @author zhangheng
     */
    public function dispute_stripe_info($config,$params = [])
    {
        //type 1拉取历史 2拉取实时创建 3实时更新
        $type    = $params['type']  ??  1;
        $api_type    = $config['api_type'];
        $url = $config['path']."".$config['disputes'];
        switch ($type) {
            case '1'://拉取历史
                $order_dispute = Db::name('order_dispute_stripe')
                    ->where(['type' => 'stripe'])
                    ->where(['api_type' => $api_type])
                    ->order('create_time asc')->find();
                    if(!empty($order_dispute)){
                        $url = $url . '&starting_after=' . $order_dispute['dispute_id'];
                    }
                break;
            case '2'://2拉取实时
                $order_dispute = Db::name('order_dispute_stripe')
                    ->where(['type' => 'stripe'])
                    ->where(['api_type' => $api_type])
                    ->order('create_time desc')->find();
                    if(!empty($order_dispute)){
                        $url = $url . '&ending_before=' . $order_dispute['dispute_id'];
                    }
                break;
            default:
        }
        //Stripe争议
        $data = HttpUtil::getUrlStripe($url,$config);
        // halt($data);
        if ($data) {
            if (!empty($data['error'])) {
                $arr_error['type'] = 'stripe_error';
                $arr_error['api_type'] = $api_type;
                $arr_error['json'] = json_encode($data, true);
                Db::name('order_dispute_stripe')->insert($arr_error);
                return $data['error']['message'];
            }
            $orders = $data['data'];
            if (is_array($orders) && !empty($orders)) {
                date_default_timezone_set('Asia/Shanghai');
                foreach ($orders as  $order) {
                    $order_info = Db::name('order_dispute_stripe')->where(['dispute_id' => $order['id']])->find();
                    $arr['type'] = 'stripe';
                    if(!empty($order['created'])){
                        $arr['create_time'] = date('Y-m-d H:i:s', $order['created']);
                    }else{
                        $arr['create_time'] = "";
                    }
                    $arr['status'] = $order['status'] ?? "";
                    $arr['api_type'] = $api_type;
                    $arr['reason'] = $order['reason'] ?? "";
                    $arr['payment_intent'] = $order['payment_intent'] ?? "";
                    $arr['amount'] = $order['amount'];
                    if(isset($order['balance_transactions'][0])){
                        $balance_transactions = $order['balance_transactions'][0];
                        if(!empty($balance_transactions)){
                            $arr['fee'] = $balance_transactions['fee'];
                        }
                    }
                    $arr['currency'] = $order['currency'] ?? "";
                    $arr['customer_email_address'] = $order['evidence']['customer_email_address'] ?? "";
                    $arr['customer_name'] = $order['evidence']['customer_name'] ?? "";
                    $arr['billing_address'] = $order['evidence']['billing_address'] ?? "";
                    $arr['shipping_address'] = $order['evidence']['shipping_address'] ?? "";
                    $arr['json'] = json_encode($order, true);
                    if ($order_info) {
                        Db::name('order_dispute_stripe')->where(['dispute_id' => $order['id']])->update($arr);
                    } else {
                        $arr['dispute_id'] = $order['id'];
                        Db::name('order_dispute_stripe')->insert($arr);
                    }
                }
            }
        }
        return true;
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc shopify-Disputes获取list
     * @author zhangheng
     */
    public function ApiOrderDisputes($params = [])
    {    
        $shop_id        = $params['shop_id'] ?? 0;
        if(empty($shop_id)){
            //轮询店铺
            $ApiOrderLogic = new ApiOrderLogic();
            $shop_id = $ApiOrderLogic->PollingStores();
            if (empty($shop_id)) {
                return json(DefaultResponse(201, false, '暂无店铺!', null));
            }
        }
        
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version . "/shopify_payments/disputes.json";

        $type = $params['type']  ??  1;
        switch ($type) {
            case '1'://拉取历史
                $order_dispute = Db::name('order_dispute_api')
                    ->where('shop_id',$shop_id)
                    ->order('initiated_at asc')->find();
                    if(!empty($order_dispute)){
                        $url = $url . '?last_id=' . $order_dispute['dispute_id'];
                    }
                break;
            case '2'://2拉取实时
                $order_dispute = Db::name('order_dispute_api')
                    ->where('shop_id',$shop_id)
                    ->order('initiated_at desc')->find();
                    if(!empty($order_dispute)){
                        $url = $url . '?since=' . $order_dispute['dispute_id'];
                    }
                break;
            default:
        }

        $return = HttpUtil::getUrl($url, $shop_info);
        // halt($return);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors'])."店铺名称：".$shop_info['name'], null));
        }

        $disputes = $return['disputes'];
        try{
            if (is_array($disputes) && !empty($disputes)) {
                date_default_timezone_set('Asia/Shanghai');
                foreach ($disputes as $dispute) {
                    $order_dispute_api = Db::name('order_dispute_api')->where('dispute_id',$dispute['id'])->find();
                    $arr = [];
                    $arr['order_id'] = $dispute['order_id'] ?? "";
                    $arr['type'] = $dispute['type'] ?? "";
                    $arr['amount'] = $dispute['amount'] ?? "";
                    $arr['currency'] = $dispute['currency'] ?? "";
                    $arr['reason'] = $dispute['reason'] ?? "";
                    $arr['network_reason_code'] = $dispute['network_reason_code'] ?? "";
                    $arr['status'] = $dispute['status'] ?? "";
                    $arr['evidence_due_by'] = $dispute['evidence_due_by'] ?? "";
                    $arr['initiated_at'] = $dispute['initiated_at'] ?? "";
                    $arr['json'] = json_encode($dispute, true);
                    $arr['shop_id'] = $shop_id;
                    if ($order_dispute_api) {
                        Db::name('order_dispute_api')->where('dispute_id',$dispute['id'])->update($arr);
                    } else {
                        $arr['dispute_id'] = $dispute['id'] ?? "";
                        Db::name('order_dispute_api')->insert($arr);
                    }
                }
                return  $this->jsonMessage(200,true,'操作成功','');
            }else{
                return  $this->jsonMessage(201,false,'暂无数据','');
            }
           }catch (\Exception $e) {
               return  $this->jsonMessage(201,false,$e->getMessage(),'');
         }
    }

    /**
    * @desc    查询订单交易API
    * @date    2024/8/24
    * @author  zhangheng
    */
    public function QueryOrderTransactionApi($params)
    {
        // $update['dispute_status'] = 0;
        // Db::name('order')
        //     ->where('createtime',">=",1719763200)
        //     ->where('createtime',"<=",1725120000)
        //     ->update($update);
        // $count = Db::name('order')
        //     ->where('createtime',">=",1719763200)
        //     ->where('createtime',"<=",1725120000)
        //     ->where('dispute_status',0)
        //     ->count();
        // halt($count);
        
        $type        = $params['type'] ?? 1;
        switch ($type) {
            case '1':
                $order = Db::name('order')
                    ->field('shop_id,order_id')
                    ->where('createtime',">=",1730390400)
                    ->where('createtime',"<=",1732982400)
                    ->where('dispute_status',0)
                    ->order('createtime asc')
                    ->find();
                    // ->count();
                    // halt($order);
                break;
            case '2':
                $order = Db::name('order')
                    ->field('shop_id,order_id')
                    ->where('createtime',">=",1725120000)
                    ->where('createtime',"<=",time())
                    ->where('dispute_status',0)
                    ->order('createtime desc')
                    ->find();
                break;
            default:
        }
        if (empty($order)) {
            return json(DefaultResponse(201, false, "类型".$type."完成", null));
        }

        
        
        $shop_id        = $order['shop_id'];
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version . "/orders/".$order['order_id']."/transactions.json";
        $return = HttpUtil::getUrl($url, $shop_info);
        if(!empty($return)){
            // Db::name('order_transactions')->where('order_id',$order['order_id'])->delete();
            $inserts = [];
            $transactions = $return['transactions'];
            foreach ($transactions as $k=>$vt) {
                $arr_transactions = [];
                $arr_transactions['order_id'] = $order['order_id'];
                $arr_transactions['shop_id'] = $shop_id;
                $arr_transactions['transactions_id'] = $vt['id'];
                $arr_transactions['status'] = $vt['status'] ?? "";
                $arr_transactions['gateway'] = $vt['gateway'] ?? "";
                $arr_transactions['message'] = $vt['message'] ?? "";
                $arr_transactions['authorization'] = $vt['authorization'] ?? "";
                $arr_transactions['amount'] = $vt['amount'] ?? "";
                $arr_transactions['currency'] = $vt['currency'] ?? "";
                $arr_transactions['payment_id'] = $vt['payment_id'] ?? "";
                $arr_transactions['kind'] = $vt['kind'] ?? "";
                $arr_transactions['created_at'] = $vt['created_at'] ?? "";
                $arr_transactions['parent_txn_id'] = 0;
                if(!empty($vt['receipt'])){
                    $arr_transactions['parent_txn_id'] = $vt['receipt']['parent_txn_id'] ?? 0;
                }
                $inserts[] = $arr_transactions;
                Db::name('order_transactions')->where('transactions_id',$arr_transactions['transactions_id'])->delete();
            }
            Db::name('order_transactions')->insertAll($inserts);
        }
        
        $update['dispute_status'] = 1;
        $order = Db::name('order')
            ->where('order_id',$order['order_id'])
            ->update($update);
        return json(DefaultResponse(200, true, '操作完成', '')); 
    }
    /**
    * @desc    查询订单交易API
    * @date    2024/8/24
    * @author  zhangheng
    */
    public function QueryOrderTransactionApiList($params)
    {
        $type           = $params['type'] ?? '2'; //1更新 2获取历史记录
        $shop_id     = $params['shop_id'] ?? 17;

        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version . "/shopify_payments/balance/transactions.json";
        switch ($type) {
            case '1':
                $last_order = Db::name('order_balance_api')
                    ->where('shop_id', $shop_id)
                    ->order('processed_at desc')
                    ->find();
                if (!empty($last_order['created_at'])) {
                    $url = $url . '?since_id=' . $last_order['balance_id'];
                }
                break;
            case '2':
                if (!empty($shop_info['balanceTime'])) {
                    $last_order = Db::name('order_balance_api')
                        ->where('processed_at', $shop_info['balanceTime'])
                        ->find();
                    $url = $url . '?last_id=' . $last_order['balance_id'];
                }
                break;
            default:
        }
        $return = HttpUtil::getUrl($url, $shop_info);
        if(!empty($return)){
            $transactions = $return['transactions'];
            $ControlUpdateTime = 0;
            foreach ($transactions as $k=>$vt) {
                $arr_transactions = [];
                $arr_transactions['shop_id'] = $shop_id;
                $arr_transactions['balance_id'] = $vt['id'];
                $arr_transactions['type'] = $vt['type'];
                $arr_transactions['test'] = $vt['test'];
                $arr_transactions['payout_id'] = $vt['payout_id'];
                $arr_transactions['payout_status'] = $vt['payout_status'];
                $arr_transactions['currency'] = $vt['currency'];
                $arr_transactions['amount'] = $vt['amount'];
                $arr_transactions['fee'] = $vt['fee'];
                $arr_transactions['net'] = $vt['net'];
                $arr_transactions['source_id'] = $vt['source_id'];
                $arr_transactions['source_type'] = $vt['source_type'];
                $arr_transactions['source_order_id'] = $vt['source_order_id'];
                $arr_transactions['processed_at'] = $vt['processed_at'];

                $order_customer = Db::name('order_balance_api')->where('balance_id',$vt['id'])->find();
                if(!empty($order_customer)){
                    Db::name('order_balance_api')->where('balance_id',$vt['id'])->update($arr_transactions);
                }else{
                    Db::name('order_balance_api')->insert($arr_transactions);
                }
                $ApiOrderLogic = new ApiOrderLogic();
                if($type == 2){
                    //移除时间字符串中的'T'和时区部分
                    if(!empty($ControlUpdateTime)){
                        if($shop_id == 20){
                            $createtime = $ApiOrderLogic->dateTimeStr($vt['processed_at']);
                            $ControlUpdateTimeTimeStamp = $ApiOrderLogic->dateTimeStr($ControlUpdateTime);
                            if($ControlUpdateTimeTimeStamp <= $createtime){
                                $ControlUpdateTime = $vt['processed_at'];
                            }
                        }else{
                            $createtime = $ApiOrderLogic->dateTimeStr($vt['processed_at']);
                            $ControlUpdateTimeTimeStamp = $ApiOrderLogic->dateTimeStr($ControlUpdateTime);
                            if($ControlUpdateTimeTimeStamp > $createtime){
                                $ControlUpdateTime = $vt['processed_at'];
                            }
                        }
                    }else{
                        $ControlUpdateTime = $vt['processed_at'];
                    }
                }
            }
            if($type == 2){
                $update_shop['balanceTime'] = $ControlUpdateTime;
                Db::name('shops')
                    ->where('id', $shop_id)
                    ->update($update_shop);
            }
        }
        return  $this->jsonMessage(200,true,'操作成功','');
    }
    

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc afterpay获取list
     * @author zhangheng
     */
    public function dispute_afterpay($params = [])
    {
        $dispute_afterpay = Config('Logisticskey.dispute_afterpay');
        foreach ($dispute_afterpay as $k=>$v) {
            $this->dispute_afterpay_info($v,$params);
        }
        return json(DefaultResponse(200, true, '操作成功'));
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc afterpay获取list
     * @author zhangheng
     */
    public function dispute_afterpay_info($config,$params = [])
    {
        //type 1拉取历史 2拉取实时创建
        $type    = $params['type']  ??  1;
        $api_type    = $config['api_type'];
        $url = $config['path']."".$config['disputes'];
        switch ($type) {
            case '1'://拉取历史
                $order_dispute = Db::name('order_dispute_afterpay')
                    ->where(['type' => 'afterpay'])
                    ->where(['api_type' => $api_type])
                    ->order('createdAt asc')->find();
                    if(!empty($order_dispute)){
                        $url = $url . '?openedBefore=' . $order_dispute['createdAt'];
                    }
                break;
            case '2'://2拉取实时
                $order_dispute = Db::name('order_dispute_afterpay')
                    ->where(['type' => 'afterpay'])
                    ->where(['api_type' => $api_type])
                    ->order('createdAt desc')->find();
                    if(!empty($order_dispute)){
                        $url = $url . '?openedAfter=' . $order_dispute['createdAt'];
                    }
                break;
            default:
        }
        $data = HttpUtil::getUrl($url,$config);
        if ($data) {
            if (!empty($data['error'])) {
                $arr_error['type'] = 'afterpay_error';
                $arr_error['api_type'] = $api_type;
                $arr_error['json'] = json_encode($data, true);
                Db::name('order_dispute_afterpay')->insert($arr_error);
                return $data['error_description'];
            }
            if (isset($data['data']) && !empty($data['data']) && is_array($data['data'])) {
                $orders = $data['data'];
                date_default_timezone_set('Asia/Shanghai');
                foreach ($orders as  $order) {
                    $dispute_info = Db::name('order_dispute_afterpay')->where('dispute_id',$order['id'])->find();
                    $arr = [];
                    $arr['updatedAt'] = $order['updatedAt'];
                    if ($dispute_info) {
                        $arr['status'] = $order['status'] ?? "";
                        if($dispute_info['updatedAt'] > strtotime($arr['updatedAt'])){
                            Db::name('order_dispute_afterpay')->where(['dispute_id' => $order['id']])->update($arr);
                        }
                    } else {
                        $arr['type'] = 'afterpay';
                        $arr['createdAt'] = $order['createdAt'];
                        $arr['order'] = $order['order'] ?? "";
                        $arr['status'] = $order['status'] ?? "";
                        $arr['amount'] = $order['amount'] ?? "";
                        $arr['currency'] = $order['currency'] ?? "";
                        $arr['reason'] = $order['reason'] ?? "";
                        $arr['open'] = $order['open'] ?? "";
                        $arr['responseDueBy'] = $order['responseDueBy'] ?? "";
                        $arr['openingNote'] = $order['openingNote'] ?? "";
                        $arr['merchantOrderId'] = $order['merchantOrderId'] ?? "";
                        $arr['transactionDate'] = $order['transactionDate'] ?? "";
                        $arr['api_type'] = $api_type;
                        
                        $arr['json'] = json_encode($order, true);
                        $arr['dispute_id'] = $order['id'];
                        Db::name('order_dispute_afterpay')->insert($arr);
                    }
                }
            }
        }
        $order_dispute = Db::name('order_dispute_afterpay')
            ->where(['type' => 'afterpay'])
            ->where(['api_type' => $api_type])
            ->order('createdAt asc')->find();
        echo $api_type.'时间是'.date('Y-m-d H:i:s',$order_dispute['createdAt']);
        return true;
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc shopify-payoutss获取list
     * @author zhangheng
     */
    public function payouts($params = [])
    {
        $shop_id        = $params['shop_id'] ?? 17;
        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version . "/shopify_payments/payouts.json";
        $type = $params['type']  ??  2;
        switch ($type) {
            case '1'://拉取历史
                $order_payouts = Db::name('order_payouts_api')
                    ->where('shop_id',$shop_id)
                    ->order('date asc')->find();
                    if(!empty($order_payouts)){
                        $url = $url . '?date_max=' . $order_payouts['date'];
                    }
                break;
            case '2'://2拉取实时
                $order_payouts = Db::name('order_payouts_api')
                    ->where('shop_id',$shop_id)
                    ->order('date desc')->find();
                    if(!empty($order_payouts)){
                        $url = $url . '?date_min=' . $order_payouts['date'];
                    }
                break;
            default:
        }
        // halt($url);
        $return = HttpUtil::getUrl($url, $shop_info);
        if (!empty($return['errors'])) {
            return json(DefaultResponse(201, false, json_encode($return['errors'])."店铺名称：".$shop_info['name'], null));
        }
        // halt($return);
        $payoutss = $return['payouts'];
        if (is_array($payoutss) && !empty($payoutss)) {
            date_default_timezone_set('Asia/Shanghai');
            foreach ($payoutss as $payouts) {
                $order_payouts_api = Db::name('order_payouts_api')->where(['payouts_id' => $payouts['id']])->find();
                
                $arr['shop_id'] = $shop_id;
                $arr['date'] = $payouts['date'] ?? "";
                $arr['status'] = $payouts['status'] ?? "";
                $arr['currency'] = $payouts['currency'] ?? "";
                $arr['amount'] = $payouts['amount'] ?? "";
                $arr['adjustments_fee_amount'] = $payouts['summary']['adjustments_fee_amount'] ?? "";
                $arr['adjustments_gross_amount'] = $payouts['summary']['adjustments_gross_amount'] ?? "";
                $arr['charges_fee_amount'] = $payouts['summary']['charges_fee_amount'] ?? "";
                $arr['charges_gross_amount'] = $payouts['summary']['charges_gross_amount'] ?? "";
                $arr['refunds_fee_amount'] = $payouts['summary']['refunds_fee_amount'] ?? "";
                $arr['refunds_gross_amount'] = $payouts['summary']['refunds_gross_amount'] ?? "";
                $arr['reserved_funds_fee_amount'] = $payouts['summary']['reserved_funds_fee_amount'] ?? "";
                $arr['reserved_funds_gross_amount'] = $payouts['summary']['reserved_funds_gross_amount'] ?? "";
                $arr['retried_payouts_fee_amount'] = $payouts['summary']['retried_payouts_fee_amount'] ?? "";
                $arr['retried_payouts_gross_amount'] = $payouts['summary']['retried_payouts_gross_amount'] ?? "";
                $arr['createtime'] = time();

                if ($order_payouts_api) {
                    Db::name('order_payouts_api')->where(['payouts_id' => $payouts['id']])->update($arr);
                } else {
                    $arr['payouts_id'] = $payouts['id'] ?? "";
                    Db::name('order_payouts_api')->insert($arr);
                }
            }
            return json(DefaultResponse(200, true, '操作完成', '')); 
        }else{
            return json(DefaultResponse(200, true, '暂无数据', '')); 
        }
        
    }

    public function ReasonForRefund($params = [])
    {
        //前端空间挤压
        $data2[0] = [
            'id' => 100000,
            'title' => "加载中",
            'sort' => 0,
        ];
        $data2[1] = [
            'id' => 100001,
            'title' => "加载中",
            'sort' => 0,
        ];
        $data2[2] = [
            'id' => 100002,
            'title' => "加载中",
            'sort' => 0,
        ];
        //前端空间挤压
        
        $data = Db::name('order_refundreason')->where('status',0)->order('sort asc')->select()->toarray();
        $data = array_merge($data2,$data);
        return $data;
    }

    
    public function ReasonForDispute($params = [])
    {
        $data = Db::name('order_disputereason')->where('status',0)->order('sort asc')->select()->toarray();
        return $data;
    }
    
    public function ReasonForDisputemsg($params = [])
    {
        $data = Db::name('order_disputemsg')->where('status',0)->order('sort asc')->select()->toarray();
        return $data;
    }

    public function addDisputeDataInfo($params = [])
    {
        $id = $params['id'] ?? 0;
        if ($id <= 0) {
            return $this->jsonMessage(201, true,'参数错误，请刷新页面');
        }
        $tabstatus = $params['tabstatus'] ?? 0;
        $where[] = ['id','=',$id];
        $update = [
            'QuestionType' => $params['QuestionType'] ?? 0,
            'ReasonForDispute' => $params['ReasonForDispute'] ?? 0,
        ];
        switch ($tabstatus) {
            case 'afterpay':
                $update = Db::name('order_dispute_afterpay')
                    ->where($where)
                    ->update($update);
                break;
            case 'airwallex':
                $update = Db::name('order_dispute_airwallex')
                    ->where($where)
                    ->update($update);
                break;
            case 'paypal':
                $update = Db::name('order_dispute_paypal')
                    ->where($where)
                    ->update($update);
                break;
            case 'stripe':
                $update = Db::name('order_dispute_stripe')
                    ->where($where)
                    ->find();
                break;
            case 'shopify':
                $update = Db::name('order_dispute_api')
                    ->where($where)
                    ->update($update);
                break;
            default:
        }
        if (!$update) {
            return $this->jsonMessage(201, true,'操作失败');
        }
        return $this->jsonMessage(200, true,'操作成功');
    }

    public function DisputeDataInfo($params = [])
    {
        $id = $params['id'] ?? 0;
        if ($id <= 0) {
            return $this->jsonMessage(200, true,'',[]);
        }
        $tabstatus = $params['tabstatus'] ?? 0;
        $where[] = ['id','=',$id];
        $list = [];
        switch ($tabstatus) {
            case 'afterpay':
                $list = Db::name('order_dispute_afterpay')
                    ->where($where)
                    ->find();
                break;
            case 'airwallex':
                $list = Db::name('order_dispute_airwallex')
                    ->where($where)
                    ->find();
                break;
            case 'paypal':
                $list = Db::name('order_dispute_paypal')
                    ->where($where)
                    ->find();
                break;
            case 'stripe':
                $list = Db::name('order_dispute_stripe')
                    ->where($where)
                    ->find();
                break;
            case 'shopify':
                $list = Db::name('order_dispute_api')
                    ->where($where)
                    ->find();
                    
                break;
            default:
        }
        return $this->jsonMessage(200, true,'',$list);
    }


    public function getProductSkus($data = [])
    {
        $shop_name = $data['shop_name'] ?? "";
        $shop_id = 0;
        switch ($shop_name) {
            case 'SheCurve':
                $shop_id = 17;
                break;
            case 'woobilly':
                $shop_id = 21;
                break;
            case 'LilyLove':
                $shop_id = 18;
                break;
            case 'kisslove':
                $shop_id = 22;
                break;
            default:
                $shop_id = 0;
        }
        // if($shop_id == 0){
        //     return $this->jsonMessage(201, true, '请先添加店铺');
        // }
        $order_number = $data['order_number'] ?? "";
        if($order_number <= 0){
            return $this->jsonMessage(200, true,'',[]);
            // return $this->jsonMessage(201, true, '请先添加订单编号');
        }
        $order_number = trim($order_number);

        $sku = Db::name('order_info')
            ->field('a.id,a.sku')
            ->alias('a')
            ->join('qu_order b','b.order_id = a.order_id', 'left')
            ->where('b.shop_id',$shop_id)
            ->where('b.order_number',$order_number)
            ->select()
            ->toarray();
        if(empty($sku)){
            // return $this->jsonMessage(201, true, '暂无SKU数据');
        }
        return $this->jsonMessage(200, true,'',$sku);
    }
    public function CustomerRefunds($data = [])
    {
        $shop_name = $data['shop_name'] ?? "";
        $shop_id = 0;
        switch ($shop_name) {
            case 'SheCurve':
                $shop_id = 17;
                break;
            case 'woobilly':
                $shop_id = 21;
                break;
            case 'LilyLove':
                $shop_id = 18;
                break;
            case 'kisslove':
                $shop_id = 22;
                break;
            default:
                $shop_id = 0;
        }
        $order_number = $data['order_number'] ?? "";
        if(!empty($shop_id) && !empty($order_number)){
            $customer_refunds = Db::name('customer_refunds')
                ->where('shop_id',$shop_id)
                ->where('order_number',$order_number)
                ->find();
            $amount = $customer_refunds['refund_payment'] ?? 0;
            if(!empty($amount)){
                $data['amount'] = $amount;
            }
            $currency = $customer_refunds['currency'] ?? "";
            if(!empty($currency)){
                $data['currency'] = $currency;
            }
            $SpecificReasons = $customer_refunds['SpecificReasons'] ?? "";
            if(!empty($SpecificReasons)){
                $data['SpecificReasons'] = $SpecificReasons;
            }
            $ReasonForRefund = $customer_refunds['ReasonForRefund'] ?? "";
            if(!empty($ReasonForRefund)){
                $data['ReasonForRefund'] = (int)$ReasonForRefund;
            }
            $Supplementary = $customer_refunds['Supplementary'] ?? "";
            if(!empty($Supplementary)){
                $data['Supplementary'] = $Supplementary;
            }
            $ProductSku = $customer_refunds['ProductSku'] ?? "";
            if(!empty($ProductSku)){
                $ProductSku = explode(',',$ProductSku);
                foreach ($ProductSku as &$v) {
                    $v = (int)$v;
                }
                
                $data['ProductSku'] = $ProductSku;
            }
        }
        return $this->jsonMessage(200, true,'',$data);
    }
}
